import { Component, Input, OnChanges } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, FormArray, Validators } from '@angular/forms';

import { Hero } from '../shared/hero.model';
import { states, heroes } from '../shared/mock-data';

@Component({
    selector: 'hero-detail-reactive-form',
    templateUrl: './hero-detail.reactive-form.component.html'
})
export class HeroDetailReactiveFormComponent implements OnChanges {
    // heroGroup = new FormGroup({
    //     name: new FormControl()
    // });

    heroGroup: FormGroup;
    states = states;
    heroes = heroes;

    @Input() hero: Hero;

    constructor(private fb: FormBuilder) {
        this.createForm();
        this.loadData(this.heroes[0]);
    }

    ngOnChanges(): void {
        this.heroGroup.reset();
        this.loadData(this.hero);
    }

    createForm(): void {
        this.heroGroup = this.fb.group({
            name: ['', Validators.required],
            address: this.fb.group({
                street: '',
                city: '',
                state: '',
                zip: ''
            }),
            power: '',
            sidekick: ''
        });
    }

    loadData(hero: Hero): void {
        // It will not accept a data object that doesn't match the FormGroup 
        // structure or is missing values for any control in the group. This way, 
        // it can return helpful error messages if you have a typo or if you've nested controls incorrectly. 
        // patchValue will fail silently. On the other hand, setValue will catch the error and report it clearly.
        this.heroGroup.setValue({
            name: hero.name,
            address: {
                street: 'New Street',
                city: 'New York',
                state: 'OH',
                zip: '000000'
            },
            power: 'flight',
            sidekick: true
        });
    }
}